package com.jiuli_travel.travel_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuli_travel.travel_service.mapper.ItinerariesMapper;
import com.jiuli_travel.travel_service.model.entity.Itineraries;
import com.jiuli_travel.travel_service.model.vo.ItinerariesVO;
import com.jiuli_travel.travel_service.service.IItinerariesService;
import com.jiuli_travel.utils.MinDistanceUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiuli
 * @since 2024-04-16
 */
@Service
public class ItinerariesServiceImpl extends ServiceImpl<ItinerariesMapper, Itineraries> implements IItinerariesService {

    // 根据搜索文本获取行程安排
    @Override
    public List<ItinerariesVO> searchItineraries(String searchText) {
        // 1. 构造查询条件并查询
        List<Itineraries> itinerariesList = lambdaQuery()
                .like(Itineraries::getTitle, searchText)
                .list();

        // 2. 查询策略, 编辑距离算法 TODO 后面引入分词器，elasticsearch 才可适配
        Map<Itineraries, Integer> itinerariesMap = new HashMap<>();
        itinerariesList.
                forEach(itineraries -> {
                    int score = MinDistanceUtil.minDistance(itineraries.getTitle(), searchText);
                    itinerariesMap.put(itineraries, score);
                });

        // 3. 根据分数进行排序
        itinerariesList = itinerariesMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 4. 转化格式
        List<ItinerariesVO> itinerariesVOS = BeanUtil.copyToList(itinerariesList, ItinerariesVO.class);
        return itinerariesVOS;
    }
}
